package com.smm.web.vmc.dao;

import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;

/**
 * Created by zhenghao on 2016/7/29.
 *
 */
@Repository
@Transactional
public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T>  {

    @Resource(name = "sessionFactory")
    public void setSuperSessionFactory(SessionFactory sessionFactory) {
        setSessionFactory(sessionFactory);
    }


    @Override
    public List<T> getAll(Class<T> clazz) {

        return getHibernateTemplate().loadAll(clazz);
    }

    @Override
    public T getOne(Class<T> clazz, Serializable id) {

        return getHibernateTemplate().get(clazz,id);
    }


    @Override
    public void update(T object) {

        getHibernateTemplate().update(object);

    }


    @Override
    public void delete(T object) {

        getHibernateTemplate().delete(object);
    }

    @Override
    public void add(T object) {

        getHibernateTemplate().save(object);
    }

    @Override
    public List<T> query(DetachedCriteria where) {

        return (List<T>) getHibernateTemplate().findByCriteria(where);
    }

    @Override
    public HibernateTemplate getTemplate(){

        return getHibernateTemplate();
    }

    @Override
    public List<Object[]> createSqlQuery(String sql) {

        return getHibernateTemplate().getSessionFactory().openSession().createNativeQuery(sql).getResultList();
    }



}
